// 云资源
<template>
  <div>
    <div class="p-15">
      <!-- 搜索条件 -->
      <el-form :model="ruleForm" ref="ruleForm" label-width="80" :inline="true">
        <el-form-item label="云资源类型: ">
          <el-select v-model="value" placeholder="请选择" clearable>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="namer">
          <el-input v-model.trim="ruleForm.namer" width="200" prefix-icon="el-icon-search" clearable placeholder="输入设备名称或设备IP"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btnSizeStyle" @click="initList()">查询</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="20" class="list" v-loading="loading" :style="{ minHeight: transferHeight.contentH + 'px' }">
        <el-col :span="12" v-if="list.length < 1">{{ message }}</el-col>
        <el-col :span="6" v-for="(item, index) in list" :key="index">
          <div class="bg-fff listItem">
            <div class="header">
              <svg class="iconfont" aria-hidden="true">
                <use xlink:href="#el-icon-myfuwuqimingcheng" />
              </svg>
              <h2>{{ item.zcmc }}</h2>
              <span :class="['tag', item.zclx === 65628 ? 'tag2' : 'tag1']">{{ item.zclx === 65628 ? '虚拟' : '实体' }}</span>
              <el-button class="btnSizeStyle seebBtn" :disabled="item.info === '' || item.zxzt !== 0" @click="seeMonitor(item)">查看</el-button>
            </div>
            <p>{{ item.info }}</p>
            <div class="footer">
              <svg class="iconfont" aria-hidden="true">
                <use :xlink:href="`#el-icon-my${item.zxzt === 0 ? 'LAN_network' : 'LAN_Nonetwork'}`" />
              </svg>
              <span>{{ item.ip }}</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 分页 -->
    <el-row class="page-row">
      <el-col :span="12"> </el-col>
      <el-col :span="12" style="height: 47px; display: table">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[12, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { zhonHe } from '@/utils/allUrl'
import { timeLoad, tableMessageText } from '@/assets/js/setTime'
import { threeLevelH } from '@/assets/js/calcHeight'
export default {
  data() {
    return {
      ruleForm: { namer: '', region: 1 },
      loading: false,
      list: [],
      message: '',
      timer: null,
      options: [
        { value: 1, label: '服务器' },
        { value: 2, label: 'PC服务器' },
        { value: 3, label: '交换机' },
        { value: 4, label: '存储' },
      ],
      value: '',
      currentPage: 1, // 页数
      pageSize: 12, // 条数
      total: 10, // 总条数
    }
  },
  computed: {
    transferHeight: function () {
      // 计算屏幕滚动高度 - nav - 导航栏
      return {
        contentH: window.innerHeight - threeLevelH - 120,
        pb: threeLevelH,
      }
    },
  },
  watch: {
    loading(newVal, oldVal) {
      this.timer = setTimeout(() => {
        if (this.loading) {
          this.loading = false
          this.list = []
          this.message = tableMessageText
        }
      }, timeLoad)
    },
  },
  created() {
    if (JSON.stringify(this.$route.params) !== '{}') {
      // 用户选中的值
      this.value = this.$route.params.selectedIndex
      // 用户输入的值
      this.ruleForm.namer = this.$route.params.searchText
    }
    this.initList()
  },
  mounted() {},
  methods: {
    // 查询列表
    async initList() {
      clearTimeout(this.loading)
      this.loading = true
      const params = new URLSearchParams()
      params.append('ZCLX_XJ', this.value)
      params.append('ZCMC_IP_XH', this.ruleForm.namer)
      params.append('ZCMC_IP_XH', this.ruleForm.namer)
      params.append('N_', this.pageSize)
      params.append('M_', this.currentPage)
      const { data: res } = await this.$http.post(`${zhonHe}milieu/findSnmp`, params)
      console.log(res)
      this.loading = false
      switch (res.code) {
        case '0000':
          this.list = res.data.list
          this.total = res.data.countList
          this.list.forEach((item) => {
            item.info = ''
            item.infoSource = {}
          })
          this.getInfo(res.data.list)
          break
        default:
          this.list = []
          this.message = res.message
          break
      }
    },
    // 改变条数
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.initList()
    },
    // 改变页数
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.initList()
    },
    // 查询服务器资源
    async getInfo(list) {
      var info_list = list
      var arr = []
      var newList = []
      info_list.forEach((item) => {
        arr.push(item.serialNo)
      })
      const arrSerialNoS = JSON.stringify(arr)
      const params = new URLSearchParams()
      params.append('arrSerialNo', arrSerialNoS)
      const { data: res } = await this.$http.post('snmp/hosts/info', params)
      switch (res.code) {
        case '0000':
          info_list.forEach((item, index) => {
            res.data.forEach((jtem) => {
              if (item.serialNo === jtem.serialNo) {
                var info = ''
                // if ((jtem.diskSpace > 0 && jtem.memory.totalMemory) > 0 || jtem.memory.diskSpace > 0) {
                // console.log(jtem.cpuNumber, '---------', jtem.memory.totalMemory)
                // diskSpace
                if (jtem.cpuNumber > 0 && jtem.memory.totalMemory) {
                  // 计算硬盘总空间 diskSpace(单位:b)
                  var diskSpace = this.formatBytes(jtem.diskSpace)
                  // 计算内存大小 memory 单位根据type
                  var totalMemory = 0
                  if (jtem.memory.type === 'kb') {
                    totalMemory = this.formatKBytes(jtem.memory.totalMemory)
                  } else {
                    totalMemory = this.formatBytes(jtem.memory.totalMemory)
                  }
                  info = `CPU ${jtem.cpuNumber}核 - 内存 ${totalMemory} - 系统盘 ${diskSpace} `
                }
                item.info = info
                item.infoSource = jtem
              }
            })
            newList.push(item)
          })
          this.list = newList
          break
        default:
          break
      }
    },
    // 跳转到详情界面
    seeMonitor(item) {
      console.log(item)
      this.$router.push({
        name: 'cloudDetails',
        query: {
          relSerialNo: item.serialNo,
          name: item.zcmc,
          searchText: this.ruleForm.namer,
          selectedIndex: this.value,
        },
      })
    },
    // 转换 单位：kb
    formatKBytes(bytes) {
      // if (bytes === 0) return '0 KB'
      // var k = 1000 // or 1024
      // var sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      // var i = Math.floor(Math.log(bytes) / Math.log(k))
      // return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
      if (bytes === 0) return '0 KB'
      var c = 1024
      var d = 2 // 默认2位
      var e = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      var f = Math.floor(Math.log(bytes) / Math.log(c))
      return parseFloat((bytes / Math.pow(c, f)).toFixed(d)) + ' ' + e[f]
    },
    // 转换单位：b
    formatBytes(bytes, last) {
      if (bytes === 0) return '0 B'
      var c = 1024
      var d = last || 2
      var e = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      var f = Math.floor(Math.log(bytes) / Math.log(c))
      return parseFloat((bytes / Math.pow(c, f)).toFixed(d)) + ' ' + e[f]
    },
  },
}
</script>

<style lang="scss" scoped>
.el-form {
  padding-top: 10px;
}
.el-form-item {
  margin-bottom: 10px;
}
.list {
  .el-col {
    padding-bottom: 15px;
    > .listItem {
      box-shadow: 0px 2px 3px 0px rgba(0, 0, 0, 0.15);
      padding: 20px 15px;
      .header {
        position: relative;
        .iconfont,
        h2,
        .tag {
          vertical-align: middle;
          padding-right: 10px;
        }
        .iconfont {
          width: 22px;
          height: 22px;
        }
        h2 {
          display: inline-block;
          font-size: 14px;
          font-weight: 600;
          // width: 60%;
          max-width: 60%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .tag {
          display: inline-block;
          height: 18px;
          line-height: 18px;
          border-radius: 9px;
          padding: 0 10px;
          font-size: 10px;
          &.tag1 {
            // 实体
            background: #f0f9eb;
            color: #67c23a;
            border: 1px solid #c2e7b0;
          }
          &.tag2 {
            // 虚拟
            background-color: #fdf6ec;
            color: #e6a23c;
            border: 1px solid #f5dab1;
          }
        }
        .seebBtn {
          padding: 0;
          border: 0;
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          color: #1989fa;
          // cursor: pointer;
          text-align: right;
          &:active {
            // color: #1989fa;
            border-color: #fff;
            outline: 0;
          }
          &:focus,
          &:hover {
            color: #409eff;
            border-color: #fff;
            background-color: #fff;
          }
          &.is-disabled {
            color: #c0c4cc;
          }
        }
      }
      > p {
        padding: 12px 0 30px;
        font-weight: 400;
        height: 28px;
        line-height: 28px;
      }
      .footer {
        .iconfont,
        span {
          vertical-align: middle;
          font-weight: 400;
        }
        .iconfont {
          width: 16px;
          height: 14px;
          padding-right: 10px;
        }
      }
    }
  }
}
.pagination {
  text-align: right;
  .el-pagination {
    margin-top: 5px;
    text-align: right;
    display: table-cell;
    vertical-align: middle;
    line-height: normal;
  }
}
</style>
